﻿using System;
using System.Data;
using DevExpress.Xpo;

namespace KamLib
{
    public class SessionConnection : IDbConnection
    {
        public Session Session { get; protected set; }
        public bool CanDisposeSession { get; protected set; }
        
        public SessionConnection(Session session, bool canDisposeSession = false)
        {
            Session = session;
            CanDisposeSession = canDisposeSession;
        }

        public void Dispose()
        {
            if (CanDisposeSession && Session != null)
                Session.Dispose();
            Session = null;
        }

        public void Open()
        {
            if (!Session.IsConnected)
                Session.Connect();
        }
        public void Close()
        {
            if (Session.IsConnected)
                Session.Disconnect();
        }

        public IDbCommand CreateCommand() { return new SessionCommand(this); }



        public IDbTransaction BeginTransaction()
        {
            Session.BeginTransaction();
            return new SessionTransaction { Connection = this };
        }
        public IDbTransaction BeginTransaction(IsolationLevel il) { return BeginTransaction(); }

        public void ChangeDatabase(string databaseName) { throw new NotImplementedException(); }

        public string ConnectionString
        {
            get { return Session.ConnectionString; }
            set { Session.ConnectionString = value; }
        }

        public int ConnectionTimeout { get { return 15; } }
        public string Database { get { throw new NotImplementedException(); } }

        public ConnectionState State
        {
            get { return Session.IsConnected ? ConnectionState.Connecting : ConnectionState.Closed; }
        }
    }
}
